package com.mq.dpca.file;

import java.io.File;
import java.io.FileOutputStream;

import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.MQConstants;
import com.ibm.mq.constants.QmgrSplCapability;
import com.mq.dpca.msg.MQConfig;
import com.mq.dpca.util.Ping;
import com.mq.dpca.util.ReadCmdLine;
import com.mq.dpca.util.RenameUtil;

/**
 * 
 * MQ
 * 
 */
public class CopyOfNewMQFileReceiver {
	private MQQueueManager qmgr; //

	private MQQueue inQueue; //

	private String queueName = "Q1"; //

	private String host = "127.0.0.1"; //

	private int port = 1414; //

	private String channel = "CH1"; //

	private String qmgrName = "QM1"; //

	private MQMessage inMsg; //

	private MQGetMessageOptions gmo; //

	private static String fileName = null; //

	private int ccsid = 0;

	private static String file_dir = null;

	private String shellName = null;

	/**
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			// 配置初始化
			CopyOfNewMQFileReceiver fileReceiver = new CopyOfNewMQFileReceiver();
			fileReceiver.initproperty();
			// 配置初始化结束
			// 队列管理器初始化
			fileReceiver.init();
			// 队列管理器初始化结束
			while (true) {
				try {
					fileReceiver.initQueue();
					fileReceiver.getDeepMsg(fileReceiver);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				try {
					Thread.sleep(1000 * 5);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 一次循环，将队列深度的消息全部取出。
	 */
	public void getDeepMsg(CopyOfNewMQFileReceiver fileReceiver) {
		int depth = 0;
		try {
			depth = inQueue.getCurrentDepth();
		} catch (Exception e) {
			// TODO: handle exception
		}
		for(int i=0;i<depth;i++){
			try {
				fileReceiver.runGoupReceiver();
				String shellname = MQConfig.getCFG(fileName);
				if (shellname != null && !"".equals(shellname)) {
					ReadCmdLine.callShell(shellname);
				} else {
					if (fileName != null)
						System.out
								.println("could not got the shell name for file :"
										+ fileName + ",Only receive files.");
				}
				if (fileReceiver.inQueue != null)
					fileReceiver.inQueue.close();
				if (fileReceiver.qmgr != null)
					fileReceiver.qmgr.close();
				fileName = null;
			} catch (Exception e) {
				// 2033
				break;
			}
		}
	}

	public void runGoupReceiver() {
		try {
			getGroupMessages();
			qmgr.commit();
			// System.out.println("\n Messages successfully Receive ");
		} catch (MQException mqe) {
			mqe.printStackTrace();
			try {
				System.out.println("\n Backing out Transaction ");
				qmgr.backout();
				// System.exit(2);
			} catch (Exception e) {
				e.printStackTrace();
				// System.exit(2);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// System.exit(2);
		} 
	}

	/**
	 * ��ʼ��������������Ϣ
	 * 
	 * @throws Exception
	 */
	private void init() throws Exception {
		/*  */
		String hosts[] = host.split(";");
		String qmgrs[] = qmgrName.split(";");
		String gt_ip = "";
		if (Ping.isAddressAvailable(hosts[0])) {
			gt_ip = hosts[0];
			qmgrName = qmgrs[0];
		} else {
			gt_ip = hosts[1];
			qmgrName = qmgrs[1];
		}
		MQEnvironment.hostname = gt_ip;
		MQEnvironment.channel = channel;
		MQEnvironment.port = port;

		/*  */
		qmgr = new MQQueueManager(qmgrName);

		/*  */
//		int opnOptn = MQConstants.MQOO_INPUT_AS_Q_DEF
//				| MQConstants.MQOO_FAIL_IF_QUIESCING;
	}
	
	public  void  initQueue()throws Exception{
		
		int opnOptn  = MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_INQUIRE;

		/*  */
		inQueue = qmgr.accessQueue(queueName, opnOptn, null, null, null);
	}

	/**
	 * 接收组消息
	 * 
	 * @throws Exception
	 */
	public void getGroupMessages() throws Exception {
		/*  */
		gmo = new MQGetMessageOptions();
		gmo.options = MQConstants.MQGMO_FAIL_IF_QUIESCING;
		gmo.options = gmo.options + MQConstants.MQGMO_SYNCPOINT;
		/*  */
		gmo.options = gmo.options + MQConstants.MQGMO_WAIT;
		/*  */
		gmo.waitInterval = 5000;
		/* */
		gmo.options = gmo.options + MQConstants.MQGMO_ALL_MSGS_AVAILABLE;
		/*  */
		gmo.options = gmo.options + MQConstants.MQGMO_LOGICAL_ORDER;
		gmo.matchOptions = MQConstants.MQMO_MATCH_GROUP_ID;
		/*  */
		inMsg = new MQMessage();
		try {
			FileOutputStream fos = null;
			/* 循环获取消息 */
			while (true) {
				try {
					inQueue.get(inMsg, gmo);
					// 如果没有输出流，则消息为消息组第一个消息。
					if (fos == null) {
						try {
							// 获取文件名
							try {
								fileName = inMsg.getStringProperty("fileName");
							} catch (Exception e) {
								System.out.println("The message receivered  without property,do nothing!");
								inMsg.clearMessage();
							}
							String fileName_full = null;
							// 获取文件存放位置
							fileName_full = file_dir
									+ RenameUtil.rename(fileName);
							fos = new FileOutputStream(new File(fileName_full));
							int msgLength = inMsg.getMessageLength();
							byte[] buffer = new byte[msgLength];
							inMsg.readFully(buffer);
							fos.write(buffer, 0, msgLength);
							/* */
							char x = gmo.groupStatus;
							if (x == MQConstants.MQGS_LAST_MSG_IN_GROUP) {
								// System.out.println("Last Msg in Group");
								break;
							}
							// inMsg.clearMessage();

						} catch (Exception e) {
							System.out
									.println("The message receivered  without property,do nothing!");
							inMsg.clearMessage();
						}
					} else {// 如果有输出流，则消息为组消息的剩余部分。
						int msgLength = inMsg.getMessageLength();
						byte[] buffer = new byte[msgLength];
						inMsg.readFully(buffer);
						fos.write(buffer, 0, msgLength);
						/*  */
						char x = gmo.groupStatus;
						if (x == MQConstants.MQGS_LAST_MSG_IN_GROUP) {
							// System.out.println("Last Msg in Group");
							break;
						}
						// inMsg.clearMessage();
					}
				} catch (Exception e) {
					// char x = gmo.groupStatus;
					// if (x == MQConstants.MQGS_LAST_MSG_IN_GROUP) {
					// System.out.println("Last Msg in Group");
					// }
					e.printStackTrace();
					break;
				}
			}
			if (fos != null)
				fos.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			//inQueue.close();
		}
	}

	public void initproperty() {
		MQConfig config = new MQConfig().MqConfig();
		if (config.getMQ_MANAGER() != null) {
			qmgrName = config.getMQ_MANAGER();
			queueName = config.getMQ_QUEUE_NAME();
			channel = config.getMQ_CHANNEL();
			host = config.getMQ_HOST_NAME();
			port = Integer.valueOf(config.getMQ_PROT());
			ccsid = Integer.valueOf(config.getMQ_CCSID());
			file_dir = config.getFILE_DIR();
		}
	}
}
